package com.ff.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ff.common.R;
import com.ff.dto.DishDto;
import com.ff.entity.Category;
import com.ff.entity.Dish;
import com.ff.entity.DishFlavor;
import com.ff.service.CategoryService;
import com.ff.service.DishFlavorService;
import com.ff.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    CacheManager cacheManager;
    //新增菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dto){
        dishService.saveWithFlavor(dto);
        return R.success("新增菜品成功");
    }

    //菜品信息分页查询
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dtoPage=new Page<>();
        QueryWrapper<Dish> queryWrapper=new QueryWrapper<>();
        if (name!=null){
            queryWrapper.like(name!=null,"name",name);
        }
        queryWrapper.orderByDesc("update_time");
        dishService.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list=new ArrayList<>();
        for (Dish dish:records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);

            Long categoryId = dish.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            list.add(dishDto);
        }
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    //根据菜品id让菜品信息回显
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }
    //保存修改后的菜品信息
    @PutMapping
    public R<String> updata(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);

        //清理所有菜品的缓存数据
        //Set keys = redisTemplate.keys("dish_*");
        //System.out.println(keys.toString());

        //清理当前分类缓存
        String key="dish_"+dishDto.getCategoryId()+"_1";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);

        return R.success("修改菜品信息成功");
    }
    //根据条件查询对应菜品数据
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dtoList=null;
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(dtoList!=null){
            return R.success(dtoList);
        }

        QueryWrapper<Dish> queryWrapper=new QueryWrapper<>();

        queryWrapper.eq("category_id",dish.getCategoryId());
        //指定正在售卖中的
        queryWrapper.eq("status",1);
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        List<Dish> dishes = dishService.list(queryWrapper);

        dtoList=new ArrayList<>();
        for (Dish tmp:dishes){
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(tmp,dishDto);
            Long categoryId = tmp.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dishDto.setCategoryName(category.getName());

            QueryWrapper<DishFlavor> wrapper=new QueryWrapper<>();
            wrapper.eq("dish_id",tmp.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(wrapper);
            dishDto.setFlavors(dishFlavorList);
            dtoList.add(dishDto);
        }
        //如果不存在，则添加缓存
        redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);
        return R.success(dtoList);
    }
}
